﻿using System;
using System.Collections.Generic;

namespace IBNet.UtilsDataStructuresAndExtensions
{
   public static class UtilFunction
   {
      /// <summary>
      /// Calculates the number of shares of stock to trade based on a 
      /// desired position size in dollars and the closing price of the stock.
      /// </summary>
      /// <param name="desiredPositionSizeInDollars">The desired position size in dollars. 
      /// If closing price * 100 is >= desiredPositionSizeInDollars 
      /// then 100 will be returned to ensure that a round lot (a multiple of 100) is traded.</param>
      /// <param name="closingPrice">The closing price of the stock to be traded.</param>
      /// <returns>The number of shares of stock to trade.</returns>
      public static int CalculateQuantityToTrade(
         int desiredPositionSizeInDollars, decimal closingPrice)
      {
         if (desiredPositionSizeInDollars <= 0)
            throw new ArgumentException("desiredPositionSizeInDollars must be greater than 0.");
         if (closingPrice <= 0)
            throw new ArgumentException("closingPrice must be greater than 0.");

         // If desiredPositionSizeInDollars is 10000 and closingPrice is $101,
         // then quantity 100 will be returned, resulting in a 100 * $101 = $11000 position.
         if (closingPrice * 100 >= desiredPositionSizeInDollars)
         {
            return 100;
         }
         else
         {
            // Example: If desiredPositionSizeInDollars is 10000 and closingPrice is $50,
            // then quantity 200 will be returned, 
            // resulting in a 200 * $50 = $10000 position.

            // Example: desiredPositionSizeInDollars == $10000 and closingPrice == $30.00:

            // 10000 / 30.00 = 333.33333
            decimal desiredPositionSizeInDollarsDividedByClosingPrice =
               desiredPositionSizeInDollars / closingPrice;

            // 333.33333 / 100 = 3.33333
            decimal desiredPositionSizeInDollarsDividedByClosingPriceDividedBy100
               = desiredPositionSizeInDollarsDividedByClosingPrice / 100;

            // Math.Floor(3.33333) = 3
            decimal floorOfDesiredPositionSizeInDollarsDividedByClosingPriceDividedBy100
               = Math.Floor(desiredPositionSizeInDollarsDividedByClosingPriceDividedBy100);

            // 3 * 100 = 300. 
            // Position size = 300 * 30.00 = $9000.
            decimal intQuantityAsDecimal
               = floorOfDesiredPositionSizeInDollarsDividedByClosingPriceDividedBy100 * 100;

            int quantity = Convert.ToInt32(intQuantityAsDecimal);
            return quantity;
         }
      }
   }
}
